package com.lz.ovuola.util.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import com.lz.ovuola.util.annotation.TargetDataSource;
import com.lz.ovuola.util.constant.DataSourceConsts;
import com.lz.ovuola.util.threadlocal.DataSourceHolder;

@Order(-10)
@Aspect
// 注解的方式配置aop
@Configuration
public class DataSourceAspect {

	@Before(PointCut.TARGET_DATA_SOURCE)
	public void changeDataSource(JoinPoint point, TargetDataSource ds)
			throws Throwable {
		if (ds == null || (!DataSourceHolder.containsDataSource(ds.value()))) {
			DataSourceHolder.setDataSource(DataSourceConsts.PRIMARY_DS);
		} else {
			DataSourceHolder.setDataSource(ds.value());
		}
	}

	@After(PointCut.TARGET_DATA_SOURCE)
	public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
		DataSourceHolder.clearDataSource();
	}

}